/**
 * JavaScript DBC Parser
 * 基于 cpp-can-parser 算法实现
 */

// Token 类型定义
const TokenType = {
    StringLiteral: 'StringLiteral',
    Separator: 'Separator',
    PositiveNumber: 'PositiveNumber',
    NegativeNumber: 'NegativeNumber',
    FloatingPointNumber: 'FloatingPointNumber',
    Number: 'Number',
    Identifier: 'Identifier',
    ArithmeticSign: 'ArithmeticSign',
    Eof: 'Eof'
};

// DBC 命令 Token 定义
const DBC_TOKENS = {
    VERSION: 'VERSION',
    NS_SECTION_1: 'NS_',
    NS_SECTION_2: '_NS',
    BIT_TIMING: 'BS_',
    NODE_DEF: 'BU_',
    MESSAGE_DEF: 'BO_',
    SIGNAL_DEF: 'SG_',
    SIGNAL_VAL_DEF: 'VAL_',
    ENV_VAR: 'EV_',
    COMMENT: 'CM_',
    ATTR_DEF: 'BA_DEF_',
    ATTR_DEF_DEFAULT: 'BA_DEF_DEF_',
    ATTR_VAL: 'BA_'
};

const NS_TOKENS = new Set([
    'NS_DESC_', 'CM_', 'BA_DEF_', 'BA_', 'VAL_', 'CAT_DEF_', 'CAT_', 'FILTER', 'BA_DEF_DEF_',
    'EV_DATA_', 'ENVVAR_DATA_', 'SGTYPE_', 'SGTYPE_VAL_', 'BA_DEF_SGTYPE_', 'BA_SGTYPE_',
    'SIG_TYPE_DEF_', 'SIG_TYPE_REF_', 'VAL_TABLE_', 'SIG_GROUP_', 'SIG_VALTYPE_',
    'SIGTYPE_VALTYPE_', 'BO_TX_BU_', 'BA_DEF_REL_', 'BA_REL_', 'BA_DEF_DEF_REL_',
    'BU_SG_REL_', 'BU_EV_REL_', 'BU_BO_REL_', 'SG_MUL_VAL_'
]);

const SUPPORTED_DBC_TOKENS = new Set([
    DBC_TOKENS.VERSION, DBC_TOKENS.BIT_TIMING, DBC_TOKENS.NODE_DEF, DBC_TOKENS.MESSAGE_DEF,
    DBC_TOKENS.SIGNAL_DEF, DBC_TOKENS.SIGNAL_VAL_DEF, DBC_TOKENS.ENV_VAR, DBC_TOKENS.COMMENT,
    DBC_TOKENS.ATTR_DEF, DBC_TOKENS.ATTR_DEF_DEFAULT, DBC_TOKENS.ATTR_VAL
]);

const UNSUPPORTED_DBC_TOKENS = new Set([
    "VAL_TABLE_", "BO_TX_BU_", "ENVVAR_DATA_",
    "SGTYPE_", "SIG_GROUP_", "NS_DESC_", "SG_MUL_VAL_",
    "CM_", "BA_DEF_", "BA_DEF_DEF_", "BA_",
    "SIG_TYPE_DEF_", "SIG_TYPE_REF_", "CAT_DEF_", "CAT_",
    "FILTER", "SIG_VALTYPE_", "SIGTYPE_VALTYPE_",
    "BA_DEF_REL_", "BA_REL_", "BA_DEF_DEF_REL_",
    "BU_SG_REL_", "BU_EV_REL_", "BU_BO_REL_",
    "EV_DATA_", "SGTYPE_VAL_", "BA_DEF_SGTYPE_", "BA_SGTYPE_"
]);

// Token 类
class Token {
    constructor(type = TokenType.Eof, image = '') {
        this.type = type;
        this.image = image;
    }

    equals(other) {
        if (typeof other === 'string') {
            // 检查是否是 TokenType（类型比较）
            if (Object.values(TokenType).includes(other)) {
                return this.type === other;
            }
            // 否则是内容比较
            return this.image === other;
        }
        if (typeof other === 'object' && other.type) {
            // 如果 other 是另一个 token 对象
            return this.type === other.type && this.image === other.image;
        }
        // 默认类型比较
        return this.type === other;
    }

    toUInt() {
        const num = parseInt(this.image, 10);
        if (isNaN(num) || num < 0) {
            throw new Error(`无法将 "${this.image}" 转换为无符号整数`);
        }
        return num;
    }

    toInt() {
        const num = parseInt(this.image, 10);
        if (isNaN(num)) {
            throw new Error(`无法将 "${this.image}" 转换为整数`);
        }
        return num;
    }

    toDouble() {
        const num = parseFloat(this.image);
        if (isNaN(num)) {
            throw new Error(`无法将 "${this.image}" 转换为浮点数`);
        }
        return num;
    }
}

// 词法分析器
class DBCTokenizer {
    constructor(content) {
        this.content = content;
        this.position = 0;
        this.line = 1;
        this.currentToken = null;
        this.tokenStack = [];
    }

    getCurrentChar() {
        return this.position < this.content.length ? this.content[this.position] : '\0';
    }

    getNextChar() {
        const char = this.getCurrentChar();
        this.position++;
        if (char === '\n') {
            this.line++;
        }
        return char;
    }

    skipWhitespace() {
        while (this.position < this.content.length) {
            const char = this.getCurrentChar();
            if (char === ' ' || char === '\t' || char === '\r' || char === '\n') {
                this.getNextChar();
            } else {
                break;
            }
        }
    }

    parseNumber() {
        let numberStr = '';
        let isFloat = false;
        let isNegative = false;

        // 处理负号
        if (this.getCurrentChar() === '-') {
            isNegative = true;
            numberStr += this.getNextChar();
        } else if (this.getCurrentChar() === '+') {
            this.getNextChar();
        }

        // 解析数字部分
        while (this.position < this.content.length) {
            const char = this.getCurrentChar();
            if (char >= '0' && char <= '9') {
                numberStr += this.getNextChar();
            } else if (char === '.' && !isFloat) {
                isFloat = true;
                numberStr += this.getNextChar();
            } else {
                break;
            }
        }

        // 检查科学计数法 (E 或 e)
        if (this.position < this.content.length && 
            (this.getCurrentChar() === 'E' || this.getCurrentChar() === 'e')) {
            isFloat = true;
            numberStr += this.getNextChar(); // 添加 E/e
            
            // 处理科学计数法的符号
            if (this.position < this.content.length && 
                (this.getCurrentChar() === '+' || this.getCurrentChar() === '-')) {
                numberStr += this.getNextChar();
            }
            
            // 解析指数部分
            while (this.position < this.content.length) {
                const char = this.getCurrentChar();
                if (char >= '0' && char <= '9') {
                    numberStr += this.getNextChar();
                } else {
                    break;
                }
            }
        }

        if (numberStr === '' || numberStr === '-' || numberStr === '+') {
            throw new Error(`无效的数字格式: ${numberStr}`);
        }

        // 确定 token 类型
        let type;
        if (isFloat) {
            type = TokenType.FloatingPointNumber;
        } else if (isNegative) {
            type = TokenType.NegativeNumber;
        } else {
            type = TokenType.PositiveNumber;
        }

        return new Token(type, numberStr);
    }

    parseStringLiteral() {
        let str = '';
        this.getNextChar(); // 跳过开始的引号

        while (this.position < this.content.length) {
            const char = this.getCurrentChar();
            if (char === '"') {
                this.getNextChar(); // 跳过结束的引号
                break;
            } else if (char === '\\') {
                this.getNextChar();
                const nextChar = this.getNextChar();
                // 处理转义字符
                switch (nextChar) {
                    case 'n': str += '\n'; break;
                    case 't': str += '\t'; break;
                    case 'r': str += '\r'; break;
                    case '\\': str += '\\'; break;
                    case '"': str += '"'; break;
                    default: str += nextChar; break;
                }
            } else {
                str += this.getNextChar();
            }
        }

        return new Token(TokenType.StringLiteral, str);
    }

    parseIdentifier() {
        let identifier = '';

        while (this.position < this.content.length) {
            const char = this.getCurrentChar();
            if ((char >= 'a' && char <= 'z') || 
                (char >= 'A' && char <= 'Z') || 
                (char >= '0' && char <= '9') || 
                char === '_') {
                identifier += this.getNextChar();
            } else {
                break;
            }
        }

        return new Token(TokenType.Identifier, identifier);
    }

    getNextToken() {
        // 如果有保存的 token，先返回它们
        if (this.tokenStack.length > 0) {
            this.currentToken = this.tokenStack.pop();
            return this.currentToken;
        }

        this.skipWhitespace();

        if (this.position >= this.content.length) {
            this.currentToken = new Token(TokenType.Eof);
            return this.currentToken;
        }

        const char = this.getCurrentChar();

        // 字符串字面量
        if (char === '"') {
            this.currentToken = this.parseStringLiteral();
            return this.currentToken;
        }

        // 数字或符号
        if (char === '-' || char === '+') {
            // 检查是否是单独的算术符号
            if (this.position + 1 < this.content.length) {
                const nextChar = this.content[this.position + 1];
                if (nextChar < '0' || nextChar > '9') {
                    this.currentToken = new Token(TokenType.ArithmeticSign, this.getNextChar());
                    return this.currentToken;
                }
            }
            this.currentToken = this.parseNumber();
            return this.currentToken;
        }

        // 标识符 (包括以数字开头的情况，但不以单纯的数字开头)
        if ((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_') {
            this.currentToken = this.parseIdentifier();
            return this.currentToken;
        }
        
        // 特殊情况：以数字开头但包含字母或下划线的标识符（如"2017_5"）
        if (char >= '0' && char <= '9') {
            // 先尝试解析数字
            const savedPos = this.position;
            const numberToken = this.parseNumber();
            
            // 检查数字后是否有标识符字符
            if (this.position < this.content.length) {
                const nextChar = this.getCurrentChar();
                if ((nextChar >= 'a' && nextChar <= 'z') || 
                    (nextChar >= 'A' && nextChar <= 'Z') || 
                    nextChar === '_') {
                    // 重置位置，作为标识符解析
                    this.position = savedPos;
                    this.currentToken = this.parseIdentifier();
                    return this.currentToken;
                }
            }
            
            // 否则就是纯数字
            this.currentToken = numberToken;
            return this.currentToken;
        }

        // 分隔符
        this.currentToken = new Token(TokenType.Separator, this.getNextChar());
        return this.currentToken;
    }

    getCurrentToken() {
        return this.currentToken;
    }

    saveToken(token) {
        this.tokenStack.push(token);
    }

    skipUntil(target) {
        while (this.position < this.content.length) {
            const token = this.getNextToken();
            if (token.type === TokenType.Eof || token.equals(target)) {
                break;
            }
        }
    }

    peekToken(expected) {
        const token = this.getNextToken();
        this.saveToken(token);
        return token.equals(expected);
    }

    assertToken(expected) {
        const token = this.getNextToken();
        if (!token.equals(expected)) {
            // 生成清晰的错误信息
            let expectedStr;
            if (Object.values(TokenType).includes(expected)) {
                expectedStr = `类型 ${expected}`;
            } else {
                expectedStr = `"${expected}"`;
            }
            
            throw new Error(`期望 ${expectedStr}, 但得到类型 "${token.type}" 内容 "${token.image}" (行 ${this.line})`);
        }
        return token;
    }
}

// CANSignal 类
class CANSignal {
    constructor(name, startBit, length, scale, offset, signedness, endianness, min = 0, max = 0, unit = '') {
        this.name = name;
        this.startBit = startBit;
        this.length = length;
        this.scale = scale;
        this.offset = offset;
        this.signedness = signedness; // 'Signed' or 'Unsigned'
        this.endianness = endianness; // 'BigEndian' or 'LittleEndian'
        this.min = min;
        this.max = max;
        this.unit = unit;
        this.comment = '';
        this.choices = {}; // 枚举值映射
    }

    setComment(comment) {
        this.comment = comment;
    }

    setChoices(choices) {
        this.choices = choices;
    }
}

// CANFrame 类
class CANFrame {
    constructor(name, canId, dlc, period = 0, comment = '') {
        this.name = name;
        this.canId = canId;
        this.dlc = dlc;
        this.period = period;
        this.comment = comment;
        this.signals = [];
        this.signalMap = new Map();
    }

    addSignal(signal) {
        this.signals.push(signal);
        this.signalMap.set(signal.name, signal);
    }

    getSignal(name) {
        return this.signalMap.get(name);
    }

    hasSignal(name) {
        return this.signalMap.has(name);
    }

    setComment(comment) {
        this.comment = comment;
    }

    setPeriod(period) {
        this.period = period;
    }
}

// CANDatabase 类
class CANDatabase {
    constructor(filename = '') {
        this.filename = filename;
        this.version = '';
        this.frames = [];
        this.frameMap = new Map();
        this.frameIdMap = new Map();
        this.nodes = [];
        this.warnings = [];
    }

    addFrame(frame) {
        this.frames.push(frame);
        this.frameMap.set(frame.name, frame);
        this.frameIdMap.set(frame.canId, frame);
    }

    getFrame(name) {
        return this.frameMap.get(name);
    }

    getFrameById(id) {
        return this.frameIdMap.get(id);
    }

    hasFrame(name) {
        return this.frameMap.has(name);
    }

    hasFrameId(id) {
        return this.frameIdMap.has(id);
    }

    addWarning(message, line) {
        this.warnings.push({ message, line });
    }
}

// DBC 解析器主类
class DBCParser {
    constructor(tokenizer) {
        this.tokenizer = tokenizer;
        this.database = new CANDatabase();
    }

    parseVersion() {
        if (this.tokenizer.peekToken(DBC_TOKENS.VERSION)) {
            this.tokenizer.getNextToken(); // 消费 VERSION token
            const versionToken = this.tokenizer.assertToken(TokenType.StringLiteral);
            this.database.version = versionToken.image;
        }
    }

    parseNSSection() {
        if (this.tokenizer.peekToken(DBC_TOKENS.NS_SECTION_1) || 
            this.tokenizer.peekToken(DBC_TOKENS.NS_SECTION_2)) {
            this.tokenizer.getNextToken(); // 消费 NS_ 或 _NS token
            this.tokenizer.assertToken(':');
            
            // 跳过所有 NS tokens
            let token = this.tokenizer.getNextToken();
            while (token.type !== TokenType.Eof && NS_TOKENS.has(token.image)) {
                token = this.tokenizer.getNextToken();
            }
            
            if (token.type !== TokenType.Eof) {
                this.tokenizer.saveToken(token);
            }
        }
    }

    parseBitTiming() {
        if (this.tokenizer.peekToken(DBC_TOKENS.BIT_TIMING)) {
            this.tokenizer.getNextToken(); // 消费 BS_ token
            this.tokenizer.assertToken(':');
            
            // 跳过比特时序配置（暂不支持）
            if (this.tokenizer.peekToken(TokenType.PositiveNumber)) {
                this.tokenizer.getNextToken(); // 波特率
                this.tokenizer.assertToken(':');
                this.tokenizer.assertToken(TokenType.PositiveNumber); // BTR1
                this.tokenizer.assertToken(',');
                this.tokenizer.assertToken(TokenType.PositiveNumber); // BTR2
            }
        }
    }

    parseNodes() {
        if (this.tokenizer.peekToken(DBC_TOKENS.NODE_DEF)) {
            this.tokenizer.getNextToken(); // 消费 BU_ token
            this.tokenizer.assertToken(':');

            // 解析节点名称列表
            const nodes = new Set();
            let token = this.tokenizer.getNextToken();
            
            while (token.type === TokenType.Identifier && !SUPPORTED_DBC_TOKENS.has(token.image)) {
                if (nodes.has(token.image)) {
                    this.database.addWarning(`重复的节点名称: ${token.image}`, this.tokenizer.line);
                } else {
                    nodes.add(token.image);
                    this.database.nodes.push(token.image);
                }
                token = this.tokenizer.getNextToken();
            }
            
            if (token.type !== TokenType.Eof) {
                this.tokenizer.saveToken(token);
            }
        }
    }

    parseSignalDefinition(frame) {
        this.tokenizer.getNextToken(); // 消费 SG_ token
        
        const nameToken = this.tokenizer.assertToken(TokenType.Identifier);
        
        // 检查是否有多路复用标记 (M, m0, m1, 等)
        let multiplexerInfo = null;
        if (this.tokenizer.peekToken(TokenType.Identifier)) {
            const muxToken = this.tokenizer.getNextToken();
            if (muxToken.image === 'M' || muxToken.image.startsWith('m')) {
                multiplexerInfo = muxToken.image;
                this.database.addWarning(`跳过多路复用信号: ${nameToken.image} (${multiplexerInfo})`, this.tokenizer.line);
            } else {
                // 如果不是多路复用标记，重新放回
                this.tokenizer.saveToken(muxToken);
            }
        }
        
        this.tokenizer.assertToken(':');
        const startBitToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
        this.tokenizer.assertToken('|');
        const lengthToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
        this.tokenizer.assertToken('@');
        const endiannessToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
        const signednessToken = this.tokenizer.assertToken(TokenType.ArithmeticSign);
        this.tokenizer.assertToken('(');
        const scaleToken = this.tokenizer.getNextToken(); // 可能是正数、负数或浮点数
        if (scaleToken.type !== TokenType.PositiveNumber && 
            scaleToken.type !== TokenType.NegativeNumber && 
            scaleToken.type !== TokenType.FloatingPointNumber) {
            throw new Error(`期望数字，但得到类型 "${scaleToken.type}" 内容 "${scaleToken.image}" (行 ${this.tokenizer.line})`);
        }
        this.tokenizer.assertToken(',');
        const offsetToken = this.tokenizer.getNextToken(); // 可能是正数、负数或浮点数
        if (offsetToken.type !== TokenType.PositiveNumber && 
            offsetToken.type !== TokenType.NegativeNumber && 
            offsetToken.type !== TokenType.FloatingPointNumber) {
            throw new Error(`期望数字，但得到类型 "${offsetToken.type}" 内容 "${offsetToken.image}" (行 ${this.tokenizer.line})`);
        }
        this.tokenizer.assertToken(')');
        this.tokenizer.assertToken('[');
        const minToken = this.tokenizer.getNextToken(); // 可能是正数、负数或浮点数
        if (minToken.type !== TokenType.PositiveNumber && 
            minToken.type !== TokenType.NegativeNumber && 
            minToken.type !== TokenType.FloatingPointNumber) {
            throw new Error(`期望数字，但得到类型 "${minToken.type}" 内容 "${minToken.image}" (行 ${this.tokenizer.line})`);
        }
        this.tokenizer.assertToken('|');
        const maxToken = this.tokenizer.getNextToken(); // 可能是正数、负数或浮点数
        if (maxToken.type !== TokenType.PositiveNumber && 
            maxToken.type !== TokenType.NegativeNumber && 
            maxToken.type !== TokenType.FloatingPointNumber) {
            throw new Error(`期望数字，但得到类型 "${maxToken.type}" 内容 "${maxToken.image}" (行 ${this.tokenizer.line})`);
        }
        this.tokenizer.assertToken(']');
        const unitToken = this.tokenizer.assertToken(TokenType.StringLiteral);
        
        // 跳过ECU列表（暂不支持）
        let ecuToken = this.tokenizer.assertToken(TokenType.Identifier);
        while (this.tokenizer.peekToken(',')) {
            this.tokenizer.getNextToken(); // 消费逗号
            ecuToken = this.tokenizer.assertToken(TokenType.Identifier);
        }

        // 检查重复信号
        if (frame.hasSignal(nameToken.image)) {
            this.database.addWarning(`帧 ${frame.canId} 中重复定义信号: ${nameToken.image}`, this.tokenizer.line);
        }

        // 创建信号对象
        const signal = new CANSignal(
            nameToken.image,
            startBitToken.toUInt(),
            lengthToken.toUInt(),
            scaleToken.toDouble(),
            offsetToken.toDouble(),
            signednessToken.image === '-' ? 'Signed' : 'Unsigned',
            endiannessToken.image === '0' ? 'BigEndian' : 'LittleEndian',
            minToken.toDouble(),
            maxToken.toDouble(),
            unitToken.image
        );

        frame.addSignal(signal);
    }

    parseMessages() {
        // 解析连续的帧定义块
        while (this.tokenizer.peekToken(DBC_TOKENS.MESSAGE_DEF)) {
            this.tokenizer.getNextToken(); // 消费 BO_ token
            
            const idToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
            
            // 帧名称可能是标识符或者以数字开头的标识符
            const nameToken = this.tokenizer.getNextToken();
            if (nameToken.type !== TokenType.Identifier && nameToken.type !== TokenType.PositiveNumber) {
                throw new Error(`期望帧名称，但得到类型 "${nameToken.type}" 内容 "${nameToken.image}" (行 ${this.tokenizer.line})`);
            }
            
            this.tokenizer.assertToken(':');
            const dlcToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
            const ecuToken = this.tokenizer.assertToken(TokenType.Identifier);

            const canId = idToken.toUInt();
            
            // 检查重复帧ID
            if (this.database.hasFrameId(canId)) {
                throw new Error(`重复的帧ID: ${canId} (行 ${this.tokenizer.line})`);
            }

            // 检查重复帧名称
            if (this.database.hasFrame(nameToken.image)) {
                this.database.addWarning(`重复的帧名称: ${nameToken.image}`, this.tokenizer.line);
            }

            // 创建帧对象
            const frame = new CANFrame(nameToken.image, canId, dlcToken.toUInt());
            
            // 解析信号定义
            while (this.tokenizer.peekToken(DBC_TOKENS.SIGNAL_DEF)) {
                this.parseSignalDefinition(frame);
            }

            this.database.addFrame(frame);
        }
    }

    parseComments() {
        while (this.tokenizer.peekToken(DBC_TOKENS.COMMENT)) {
            this.tokenizer.getNextToken(); // 消费 CM_ token
            
            if (this.tokenizer.peekToken(TokenType.StringLiteral)) {
                // 全局注释（暂不支持）
                this.tokenizer.getNextToken();
                // 尝试消费分号，如果没有就忽略
                if (this.tokenizer.peekToken(';')) {
                    this.tokenizer.getNextToken();
                }
                this.database.addWarning('不支持的全局注释', this.tokenizer.line);
                continue;
            }

            // 检查下一个token，可能是标识符或直接是数字（简化的注释格式）
            const nextToken = this.tokenizer.getNextToken();
            
            if (nextToken.type === TokenType.PositiveNumber) {
                // 简化的注释格式：CM_ frameId "comment"
                const frameId = nextToken.toUInt();
                const commentToken = this.tokenizer.assertToken(TokenType.StringLiteral);
                // 尝试消费分号，如果没有就忽略
                if (this.tokenizer.peekToken(';')) {
                    this.tokenizer.getNextToken();
                }
                
                if (this.database.hasFrameId(frameId)) {
                    this.database.getFrameById(frameId).setComment(commentToken.image);
                } else {
                    this.database.addWarning(`帧 ${frameId} 不存在，无法设置注释`, this.tokenizer.line);
                }
                continue;
            }
            
            if (nextToken.type !== TokenType.Identifier) {
                // 未知的注释格式，跳过
                this.database.addWarning('未知的注释格式', this.tokenizer.line);
                this.tokenizer.skipUntil(';');
                continue;
            }
            
            const commentTypeToken = nextToken;
            
            if (commentTypeToken.equals(DBC_TOKENS.MESSAGE_DEF)) {
                // 消息注释
                const frameIdToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
                const commentToken = this.tokenizer.assertToken(TokenType.StringLiteral);
                // 尝试消费分号，如果没有就忽略
                if (this.tokenizer.peekToken(';')) {
                    this.tokenizer.getNextToken();
                }

                const frameId = frameIdToken.toUInt();
                if (this.database.hasFrameId(frameId)) {
                    this.database.getFrameById(frameId).setComment(commentToken.image);
                } else {
                    this.database.addWarning(`帧 ${frameId} 不存在，无法设置注释`, this.tokenizer.line);
                }
            } else if (commentTypeToken.equals(DBC_TOKENS.SIGNAL_DEF)) {
                // 信号注释
                const frameIdToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
                const signalNameToken = this.tokenizer.assertToken(TokenType.Identifier);
                const commentToken = this.tokenizer.assertToken(TokenType.StringLiteral);
                // 尝试消费分号，如果没有就忽略
                if (this.tokenizer.peekToken(';')) {
                    this.tokenizer.getNextToken();
                }

                const frameId = frameIdToken.toUInt();
                if (this.database.hasFrameId(frameId)) {
                    const frame = this.database.getFrameById(frameId);
                    if (frame.hasSignal(signalNameToken.image)) {
                        frame.getSignal(signalNameToken.image).setComment(commentToken.image);
                    } else {
                        this.database.addWarning(`信号 ${signalNameToken.image} 在帧 ${frameId} 中不存在`, this.tokenizer.line);
                    }
                } else {
                    this.database.addWarning(`帧 ${frameId} 不存在，无法设置信号注释`, this.tokenizer.line);
                }
            } else {
                // 其他类型注释（暂不支持）
                this.database.addWarning('不支持的注释类型', this.tokenizer.line);
                this.tokenizer.skipUntil(';');
            }
        }
    }

    parseAttributes() {
        while (this.tokenizer.peekToken(DBC_TOKENS.ATTR_VAL)) {
            this.tokenizer.getNextToken(); // 消费 BA_ token
            
            const attrTypeToken = this.tokenizer.assertToken(TokenType.StringLiteral);
            
            if (attrTypeToken.image === 'GenMsgCycleTime' || attrTypeToken.image === 'CycleTime') {
                this.tokenizer.assertToken('BO_');
                const frameIdToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
                const periodToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
                this.tokenizer.assertToken(';');

                const frameId = frameIdToken.toUInt();
                if (this.database.hasFrameId(frameId)) {
                    this.database.getFrameById(frameId).setPeriod(periodToken.toUInt());
                } else {
                    this.database.addWarning(`帧 ${frameId} 不存在，无法设置周期`, this.tokenizer.line);
                }
            } else {
                // 其他属性（暂不支持）
                this.database.addWarning('不支持的属性操作', this.tokenizer.line);
                this.tokenizer.skipUntil(';');
            }
        }
    }

    parseValueDescriptions() {
        while (this.tokenizer.peekToken(DBC_TOKENS.SIGNAL_VAL_DEF)) {
            this.tokenizer.getNextToken(); // 消费 VAL_ token
            
            const frameIdToken = this.tokenizer.assertToken(TokenType.PositiveNumber);
            const signalNameToken = this.tokenizer.assertToken(TokenType.Identifier);
            
            const choices = {};
            
            // 解析值描述对
            while (!this.tokenizer.peekToken(';') && !this.tokenizer.peekToken(TokenType.Eof)) {
                const valueToken = this.tokenizer.getNextToken();
                
                // 如果下一个token是数字，说明开始了新的VAL_定义，需要回退
                if ((valueToken.type === TokenType.PositiveNumber || valueToken.type === TokenType.NegativeNumber) && 
                    this.tokenizer.peekToken(TokenType.Identifier)) {
                    // 检查再下一个token是否是PositiveNumber，这样就是新的VAL_定义
                    const nextToken = this.tokenizer.getNextToken();
                    if (nextToken.type === TokenType.Identifier) {
                        const afterNext = this.tokenizer.getNextToken();
                        if (afterNext.type === TokenType.PositiveNumber || afterNext.type === TokenType.NegativeNumber) {
                            // 这是新的VAL_定义，回退所有token
                            this.tokenizer.saveToken(afterNext);
                            this.tokenizer.saveToken(nextToken);
                            this.tokenizer.saveToken(valueToken);
                            break;
                        } else {
                            // 不是新的VAL_定义，回退并继续解析
                            this.tokenizer.saveToken(afterNext);
                            this.tokenizer.saveToken(nextToken);
                        }
                    } else {
                        this.tokenizer.saveToken(nextToken);
                    }
                }
                
                // 期望下一个是字符串描述
                const nextToken = this.tokenizer.getNextToken();
                if (nextToken.type !== TokenType.StringLiteral) {
                    // 如果不是字符串，可能遇到了错误或新的定义，直接结束这个VAL_
                    this.database.addWarning(`VAL_定义意外结束，期望字符串但得到: ${nextToken.image}`, this.tokenizer.line);
                    this.tokenizer.saveToken(nextToken);
                    break;
                }
                
                choices[valueToken.toInt()] = nextToken.image;
            }
            
            // 尝试消费分号，如果没有就忽略
            if (this.tokenizer.peekToken(';')) {
                this.tokenizer.getNextToken();
            }

            const frameId = frameIdToken.toUInt();
            if (this.database.hasFrameId(frameId)) {
                const frame = this.database.getFrameById(frameId);
                if (frame.hasSignal(signalNameToken.image)) {
                    frame.getSignal(signalNameToken.image).setChoices(choices);
                } else {
                    this.database.addWarning(`信号 ${signalNameToken.image} 在帧 ${frameId} 中不存在`, this.tokenizer.line);
                }
            } else {
                this.database.addWarning(`帧 ${frameId} 不存在，无法设置信号值描述`, this.tokenizer.line);
            }
        }
    }

    skipUnsupportedSection(sectionName) {
        while (this.tokenizer.peekToken(sectionName)) {
            this.database.addWarning(`跳过不支持的指令: ${sectionName}`, this.tokenizer.line);
            this.tokenizer.getNextToken(); // 消费指令令牌
            
            try {
                // 特殊处理 VAL_TABLE_ 语法
                if (sectionName === 'VAL_TABLE_') {
                    // VAL_TABLE_ table_name value1 "description1" value2 "description2" ... ;
                    const tableNameToken = this.tokenizer.getNextToken(); // table_name
                    if (tableNameToken.type !== TokenType.Identifier && tableNameToken.type !== TokenType.PositiveNumber) {
                        // 如果不是合法的表名，跳到分号
                        this.tokenizer.saveToken(tableNameToken);
                        this.tokenizer.skipUntil(';');
                        continue;
                    }
                    
                    // 解析值描述对直到遇到分号
                    while (!this.tokenizer.peekToken(';')) {
                        const valueToken = this.tokenizer.getNextToken(); // value (数字或标识符)
                        if (valueToken.type === TokenType.Eof) break;
                        
                        if (this.tokenizer.peekToken(TokenType.StringLiteral)) {
                            this.tokenizer.getNextToken(); // description
                        } else {
                            // 如果没有字符串描述，可能格式错误，跳到分号
                            this.tokenizer.saveToken(valueToken);
                            this.tokenizer.skipUntil(';');
                            break;
                        }
                    }
                    if (!this.tokenizer.peekToken(TokenType.Eof)) {
                        this.tokenizer.assertToken(';');
                    }
                } else {
                    // 对于其他类型，跳到分号
                    this.tokenizer.skipUntil(';');
                }
            } catch (error) {
                // 如果解析VAL_TABLE_失败，简单跳到分号
                this.database.addWarning(`VAL_TABLE_ 解析错误，跳过: ${error.message}`, this.tokenizer.line);
                this.tokenizer.skipUntil(';');
            }
        }
    }

    parse() {
        try {
            // 按照 cpp-can-parser 的解析顺序
            this.parseVersion();
            this.parseNSSection();
            this.parseBitTiming();
            this.parseNodes();
            
            // 主解析循环 - 动态处理所有剩余内容
            let token = this.tokenizer.getNextToken();
            while (token.type !== TokenType.Eof) {
                if (token.equals(DBC_TOKENS.MESSAGE_DEF)) {
                    // 解析帧定义
                    this.tokenizer.saveToken(token);
                    this.parseMessages();
                } else if (token.equals(DBC_TOKENS.COMMENT)) {
                    // 解析注释
                    this.tokenizer.saveToken(token);
                    this.parseComments();
                } else if (token.equals(DBC_TOKENS.ATTR_VAL)) {
                    // 解析属性
                    this.tokenizer.saveToken(token);
                    this.parseAttributes();
                } else if (token.equals(DBC_TOKENS.SIGNAL_VAL_DEF)) {
                    // 解析值描述
                    this.tokenizer.saveToken(token);
                    this.parseValueDescriptions();
                } else if (UNSUPPORTED_DBC_TOKENS.has(token.image)) {
                    // 处理不支持的令牌
                    this.tokenizer.saveToken(token);
                    this.skipUnsupportedSection(token.image);
                } else if (SUPPORTED_DBC_TOKENS.has(token.image) || NS_TOKENS.has(token.image)) {
                    this.database.addWarning(`意外位置的支持令牌: ${token.image}`, this.tokenizer.line);
                    this.tokenizer.skipUntil(';');
                } else {
                    this.database.addWarning(`跳过未知令牌: ${token.image}`, this.tokenizer.line);
                    this.tokenizer.skipUntil(';');
                }
                token = this.tokenizer.getNextToken();
            }

            return this.database;
        } catch (error) {
            const lineInfo = this.tokenizer && this.tokenizer.line ? this.tokenizer.line : '未知';
            throw new Error(`解析失败 (行 ${lineInfo}): ${error.message}`);
        }
    }
}

// 主解析函数
function parseDBCContent(content, filename = '') {
    const tokenizer = new DBCTokenizer(content);
    const parser = new DBCParser(tokenizer);
    const database = parser.parse();
    database.filename = filename;
    return database;
}

// 导出给外部使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        parseDBCContent,
        CANDatabase,
        CANFrame,
        CANSignal,
        DBCTokenizer,
        DBCParser
    };
} 